package com.borrow.jiemihua.mainUI;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.borrow.jiemihua.R;
import com.borrow.jiemihua.base.BaseConstant;
import com.borrow.jiemihua.base.BaseFragmentActivity;
import com.borrow.jiemihua.base.URLConstant;
import com.borrow.jiemihua.mainUI.activity.LoginRegister.LoginActivity;
import com.borrow.jiemihua.mainUI.fragment.BorrowFragment;
import com.borrow.jiemihua.mainUI.fragment.HotFragment;
import com.borrow.jiemihua.mainUI.fragment.PersonFragment;
import com.borrow.jiemihua.utils.GetChannelNameUtils;
import com.borrow.jiemihua.utils.SharedPreferencesUtils;
import com.borrow.jiemihua.utils.xutils3.MyCallBack;
import com.borrow.jiemihua.utils.xutils3.XUtil;
import com.umeng.socialize.UMShareAPI;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends BaseFragmentActivity implements View.OnClickListener {
    private TextView rt_borrow,rt_borrow3;
    private TextView rt_person;
    public int mCurrentSelectIndex = 0;
    public static final String SELECT_INDEX = "selectIndex";
    public static final String CACHE_SELECT_INDEX = "cacheSelectIndex";
    public static final int INDEX_BORROW = 0;
    public static final int INDEX_PERSON = 1;
    public static final int INDEX_HOT = 3;

    private Fragment borrowFragment;
    private Fragment personFragment;
    private Fragment hotFragment;
    private FrameLayout auto_content;
    private ImageView iv_main_bottom;
    private ImageView iv_main_bottom2,iv_main_bottom3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }
        initData();
        initView();
        upTJPAUData();
        upSetGTData();

        if (savedInstanceState != null) {
            mCurrentSelectIndex = savedInstanceState.getInt(CACHE_SELECT_INDEX, INDEX_BORROW);
        } else {
            mCurrentSelectIndex = INDEX_BORROW;
        }
        selectTab(mCurrentSelectIndex);

    }

    protected void initView() {
        auto_content = (FrameLayout) findViewById(R.id.auto_content);
        rt_borrow = (TextView) findViewById(R.id.rt_borrow);
        rt_borrow3= (TextView) findViewById(R.id.rt_borrow3);
        rt_person = (TextView) findViewById(R.id.rt_person);
        iv_main_bottom= (ImageView) findViewById(R.id.iv_main_bottom);
        iv_main_bottom2= (ImageView) findViewById(R.id.iv_main_bottom2);
        iv_main_bottom3= (ImageView) findViewById(R.id.iv_main_bottom3);

        rt_borrow.setOnClickListener(this);
        rt_borrow3.setOnClickListener(this);
        rt_person.setOnClickListener(this);
        findViewById(R.id.ll_main_bt1).setOnClickListener(this);
        findViewById(R.id.ll_main_bt2).setOnClickListener(this);
        findViewById(R.id.ll_main_bt3).setOnClickListener(this);

        selectTab(INDEX_BORROW);
    }

    protected void initData() {

    }

    public void selectTab(int postion) {
        this.mCurrentSelectIndex = postion;
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        hideFragment(transaction);
        switch (postion) {
            case INDEX_BORROW:
                mImmersionBar.statusBarDarkFont(true).init();
                borrowFragment = fm.findFragmentByTag(BorrowFragment.class.getSimpleName());
                if (borrowFragment == null) {
                    borrowFragment = new BorrowFragment();
                    transaction.add(R.id.auto_content, borrowFragment, BorrowFragment.class.getSimpleName());
                } else {
                    transaction.show(borrowFragment);
                }

                iv_main_bottom.setImageResource(R.mipmap.home_icon_pre);
                rt_borrow.setTextColor(getResources().getColor(R.color.text_main));
                iv_main_bottom3.setImageResource(R.mipmap.home_hot);
                rt_borrow3.setTextColor(getResources().getColor(R.color.text_9));

                iv_main_bottom2.setImageResource(R.mipmap.home_mine);
                rt_person.setTextColor(getResources().getColor(R.color.text_9));
                break;
            case INDEX_PERSON:
                mImmersionBar.statusBarDarkFont(true).init();
                personFragment = fm.findFragmentByTag(PersonFragment.class.getSimpleName());
                if (personFragment == null) {
                    personFragment = new PersonFragment();
                    transaction.add(R.id.auto_content, personFragment, PersonFragment.class.getSimpleName());
                } else {
                    transaction.show(personFragment);
                }

                rt_person.setTextColor(getResources().getColor(R.color.text_main));
                iv_main_bottom2.setImageResource(R.mipmap.home_mine_pre);

                iv_main_bottom3.setImageResource(R.mipmap.home_hot);
                rt_borrow3.setTextColor(getResources().getColor(R.color.text_9));

                iv_main_bottom.setImageResource(R.mipmap.home_icon);
                rt_borrow.setTextColor(getResources().getColor(R.color.text_9));
               break;
            case INDEX_HOT:
                mImmersionBar.statusBarDarkFont(false).init();
                hotFragment = fm.findFragmentByTag(HotFragment.class.getSimpleName());
                if (hotFragment == null) {
                    hotFragment = new HotFragment();
                    transaction.add(R.id.auto_content, hotFragment, HotFragment.class.getSimpleName());
                } else {
                    transaction.show(hotFragment);
                }
                iv_main_bottom.setImageResource(R.mipmap.home_icon);
                rt_borrow.setTextColor(getResources().getColor(R.color.text_9));

                iv_main_bottom3.setImageResource(R.mipmap.home_hot_pre);
                rt_borrow3.setTextColor(getResources().getColor(R.color.text_main));

                iv_main_bottom2.setImageResource(R.mipmap.home_mine);
                rt_person.setTextColor(getResources().getColor(R.color.text_9));

                break;
            default:break;
        }
        transaction.commit();

    }
    private void hideFragment(FragmentTransaction transaction) {
        if (borrowFragment != null) {
            transaction.hide(borrowFragment);
        }
        if (hotFragment != null) {
            transaction.hide(hotFragment);
        }
        if (personFragment != null) {
            transaction.hide(personFragment);
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_main_bt1:
            case R.id.rt_borrow:
                selectTab(INDEX_BORROW);
                break;
            case R.id.ll_main_bt2:
            case R.id.rt_person:
                String userid = SharedPreferencesUtils.getString(this, BaseConstant.SPConstant.USERID, "");
                if (!userid.equals("")&&userid!=null){
                    selectTab(INDEX_PERSON);
                }else{
                    startActivity(new Intent(this,LoginActivity.class));
                }
                break;
            case R.id.ll_main_bt3:
            case R.id.rt_borrow3:
                selectTab(INDEX_HOT);
                break;
            default:break;
        }
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        int selectIndex = -1;
        if (getIntent() != null && getIntent().hasExtra(SELECT_INDEX)) {
            selectIndex = getIntent().getIntExtra(SELECT_INDEX, -1);
            if (selectIndex != -1) {
                selectTab(selectIndex);
            }
        }
    }
    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        outState.putInt(CACHE_SELECT_INDEX, mCurrentSelectIndex);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        mCurrentSelectIndex = savedInstanceState.getInt(SELECT_INDEX);
        selectTab(mCurrentSelectIndex);
        super.onRestoreInstanceState(savedInstanceState);
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            selectTab(INDEX_BORROW);
        }
    }
    private long exitTime = 0;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次后退键退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("FOFOFOF","des");
    }

    @Override
    protected void onResume() {
        super.onResume();
        upSetGTData();
    }

    private void upTJPAUData(){
        Map<String,Object> map=new HashMap<>();
        String qudao=GetChannelNameUtils.getChannelName(this)+"-Android";
        map.put("source",qudao );
        Log.i("==统计PAU渠道",qudao);
        XUtil.Post(URLConstant.TONGJIPAOUA,map,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("==统计PAU",result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("isSuccess");
                    String data = jsonObject.optString("data");
                    if(res.equals("1")){
                        if(data.equals("")&&data!=null){

                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
            }
        });
    }
    private void upSetGTData(){
        Map<String,Object> map=new HashMap<>();
        String qudao=GetChannelNameUtils.getChannelName(this)+"-Android";
        String userid = SharedPreferencesUtils.getString(this, BaseConstant.SPConstant.USERID, "");
        String clientid = SharedPreferencesUtils.getString(this, BaseConstant.SPConstant.clientid, "");
        if(userid==null&&userid.equals("")){
            return;
        }
        map.put("device","1" );
        map.put("userId",userid );
        map.put("cid",clientid );
//        Log.i("==setGT",clientid);
        XUtil.Post(URLConstant.SETGETUISUER,map,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("==setGT",result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("isSuccess");
                    if(res.equals("1")){

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
